function $(e){return document.getElementById(e);}

var SPEED_PER_SEC = 0.5;

var userDataFormat = ["t", "x", "y", "dx", "dy"];
var userData = (function(){
	var d = {};
	for (var i = 0; i < userDataFormat.length; i++) {
		d[userDataFormat[i]] = undefined;
	}
	return d;
});
var me;
var people;

function loadUserData(gid, func) {
	var params = {};
	params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
	params[opensocial.IdSpec.Field.GROUP_ID] = gid;
	var idSpec = opensocial.newIdSpec(params);
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonAppDataRequest(idSpec, userDataFormat), "response");
	req.send(function(data){
		var response = data.get("response").getData();
		func(response);
	});
}

$('main').onclick = function(e){
	// 時間、目的地、を更新
	people[me]["t"] = (new Date()).getTime();
	people[me]["x"] = people[me]["dx"];
	people[me]["y"] = people[me]["dy"];
	people[me]["dx"] = e.clientX;
	people[me]["dy"] = e.clientY;
	
	// 時間、位置情報、目的地の送信
	var req = opensocial.newDataRequest();
	for (var i = 0; i < userDataFormat.length; i++) {
		var c = userDataFormat[i];
		req.add(req.newUpdatePersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, c, people[me][c]), "response");
	}
	req.send(function(data){
		if (data.hadError()) {
			var msg = data.getErrorMessage();
		} else {
			var response = data.get("response");
			if (response.hadError()) {
				var code = response.getErrorCode();
			} else {
				// success
			}
		}
	});
}

function parseUserData(src) {
	var dest = {};
	for (var i = 0; i < userDataFormat.length; i++) {
		var c = userDataFormat[i];
		dest[c] = src[c];
	}
	
	return dest;
}

// 現在位置を算出
function getNowXY(p, now) {
	var t = p["t"];
	var x = p["x"];
	var y = p["y"];
	var dx = p["dx"];
	var dy = p["dy"];
	
	// 総移動距離を算出
	var sx = (dx - x);
	var sy = (dy - y);
	var distance = sx * sx + sy * sy;
	
	// 到着予定時間 = 移動距離 ÷ 速度 + 移動開始時刻
	var arrival = distance / SPEED_PER_MILLI + t;
	
	// 現在位置を取得
	var n = {};
	n.x = ((arrival - now) * x + now * dx) / arrival;
	n.y = ((arrival - now) * y + now * dy) / arrival;
	
	return n;
}

// 時間取得
function loadTimer(){
	var url = "http://your.server.host/recent";
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.FEED;
	var post_data = {span : 7};
	params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(post_data);
	params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.NONE;
	gadgets.io.makeRequest(url, function(response) {
		var feed = response.data;
		var title = feed.Title;
		var link = feed.Link;
		// do something...
		var entries = feed.Entry;
		for (var i = 0; i < entries.length; i++) {
			var entry = entries[i];
			var entryTitle = entry.Title;
			var entryLink = entry.Link;
			// do something...
		}
	}, params);
}

// 初期化
(function(){
	// 自分の座標読み込み
	loadUserData("SELF", function(response){
		alert("test");
		
		for (var id in response) {
			people[id] = parseUserData(response[id]);
			
			var div = document.createElement('div');
			div.innerHTML = id;
			div.style.backgroundColor = "white";
			div.style.color = "red";
			div.style.position = "absorule";
			div.style.left = people[id]["x"];
			div.style.top = people[id]["y"];
			people[id]["chara"] = div;
		}
		
		alert("me " + id);
		me = id;
		
		// 自分が読み込めたらとりあえずゲームスタート
		main();
	});
})();

// ゲームメイン
function main(){
	var canvas = $('main');
	
	// 移動用タイマー
	setInterval(function(){
		var id, p;
		for (id in people) {
			p = getNowXY(people[id]);
			people[id]["chara"].style.left = p.x;
			people[id]["chara"].style.top = p.y;
		}
	}, 100);
	
	// ロード用タイマー
	setInterval(function(){
		// 友達座標読み込み
		loadUserData(opensocial.IdSpec.GroupId.FRIENDS, function(response){
			for (var id in response) {
				people[id] = parseUserData(response[id]);
				
				var div = document.createElement('div');
				div.innerHTML = id;
				div.style.backgroundColor = "white";
				div.style.color = "red";
				div.style.position = "absorule";
				div.style.left = people[id]["x"];
				div.style.top = people[id]["y"];
				people[id]["chara"] = div;
				
				canvas.appendChild(img);
			}
		});
	}, 1000);
}
